/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swe.chums.utils;

import com.swe.chums.dao.factory.DaoFactory;
import com.swe.chums.dao.model.UserActivity;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

/**
 *
 * @author cilingir
 */
public class CommonUtils {
    
    private static Logger log = Logger.getLogger(CommonUtils.class);
    private static Properties properties;
    
    /**
     * Converts string to md5
     *
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String convertMd5(String key) throws NoSuchAlgorithmException {

        log.debug("[CommonUtils.convertMd5] - md5 started for " + key);
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(key.getBytes());
        byte[] digest = md.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String md5pass = bigInt.toString(16);
        while (md5pass.length() < 32) {
            md5pass = "0" + md5pass;
        }

        return md5pass;
    }
    
    
    /**
     * Generate random string for password in the given size
     *
     * @param charSize
     * @return
     */
    public static String generatePass(int charSize) {

        Random rand = new Random();
        String response;
        StringBuilder responseBuffer = new StringBuilder();
        for (int i = 0; i < charSize; i++) {
            int num = rand.nextInt(10);
            responseBuffer.append(num);
        }
        response = responseBuffer.toString();
        log.debug("[CommonUtils.generatePass] - generated " + response);

        return response;
    }
    
    
    /**
     * Check if string is alphanumerical
     *
     * @param input
     * @return
     */
    public static boolean isAlphaNumerical(String input) {
        // Accepted characters are string, numbers and special characters ._- space
        Pattern allowed = Pattern.compile("^[a-zA-Z0-9çÇğĞıİöÖşŞüÜ _.-]*$");
        if (input == null) {
            return false;
        } else {
            Matcher m = allowed.matcher(input);
            return m.matches();
        }
    }
    
    
    /**
     * Check if the string is in allowed length
     *
     * @param input
     * @param length
     * @return
     */
    public static boolean isAllowedLength(String input, int length) {

        if (input == null) {
            return false;
        } else {
            if (input.trim().length() > length) {
                return false;
            } else {
                return true;
            }
        }
    }
    
    
    public static Properties getSystemProperties() {
        log.debug("[CommonUtils.getSystemProperties] - started");
        FileInputStream defaultsIn = null;
        properties = new Properties();
        try {
            InputStream inStream = Thread.currentThread().getContextClassLoader()
                 .getResourceAsStream("/resources/system/System.properties");
            if (inStream != null) {
                properties.load(inStream);
            }
//            URL url = CommonUtils.class.getResource("/resources/system/System.properties");
//            File file = new File(url.getFile());
//            defaultsIn = new FileInputStream(file);
//            properties.load(defaultsIn);
        } catch (FileNotFoundException ex) {
            log.error("[CommonUtils.getSystemProperties] - error: " + ex.getMessage());
        } catch (IOException ex) {
            log.error("[CommonUtils.getSystemProperties] - error: " + ex.getMessage());
        }  finally {
//            try {
//                if (defaultsIn != null) {
//                    defaultsIn.close();
//                }
//            } catch (FileNotFoundException ex) {
//                log.error("[CommonUtils.getSystemProperties] - error: " + ex.getMessage());
//            } catch (IOException ex) {
//                log.error("[CommonUtils.getSystemProperties] - error: " + ex.getMessage());
//            }
        }
        return properties;
    }
    
    
    public static void sendMail(String to, String username, String password, String subject, String text) throws Exception {
        
        log.debug("[CommonUtils.sendMail] - will send mail to: " + to);
        FacesContext context = FacesContext.getCurrentInstance();
        ResourceBundle bundle = ResourceBundle.getBundle("resources.i18n.MessageResources", context.getViewRoot().getLocale());

        //Properties props = new Properties();
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
		
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.auth", "true");
	props.setProperty("mail.smtp.port", "465");
        
        // Get session instance from smtp host
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {

                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("chumsweb", "chumsweb1");
                    }
                });
        //Session session = Session.getDefaultInstance(props);

        try {

            // Initialize message
            //Message message = new MimeMessage(session);
            MimeMessage message = new MimeMessage(session);
            String from = "chumsweb@gmail.com";
            message.setHeader("Content-Encoding", "ISO-8859-9");
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSentDate(new Date());
            message.setSubject(subject, "UTF-8");
            message.setContent(text, "text/html; charset=UTF-8");
            
            // Send mail
            Transport.send(message);

        } catch (MessagingException e) {
            log.error("[CommonUtils.sendMail] - eror while sending mail to: " + to + ", message is: " + e.getMessage());
            throw new Exception("Email send error");
        }
    }
    
    /**
     * Record user action to DB
     *
     * @param userID
     * @param userActionTypeEnum
     * @param actionItem
     */
    public static void recordUserAction(int userID, UserActivityTypeEnum userActivityTypeEnum, int webResourceID, String activityValue) {

        int userActivityTypeID = userActivityTypeEnum.getId();

        UserActivity activity = new UserActivity();

        activity.setUserId(userID);
        activity.setActivityTypeId(userActivityTypeID);
        activity.setTime(new Date());
        if (activityValue == null) {
            activityValue = "";
        }
        activity.setActivityValue(activityValue);
        activity.setWebResourceId(webResourceID);
        
        // Insert user action
        DaoFactory.createUserActivityDao().insert(activity);
    }
    
    
    public static String reconstructSearchText(String searchText) {
        
        searchText = searchText.replace(" ", "%20");
        
        return searchText;
    }
}
